package ch14;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Counter3 extends Applet implements Runnable{

	private int count = 0;
	private boolean runFlag = true;
	private Thread selfThread = null;
	private Button 
		onOff = new Button("toggle"),
		start = new Button("start");
	private TextField t = new TextField(10);
	
	public void init(){
		add(t);
		start.addActionListener(new StartL());
		add(start);
		onOff.addActionListener(new onOffL());
		add(onOff);
	}
	class StartL implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if(selfThread == null){
				selfThread = new Thread(Counter3.this);
				
				selfThread.start();
			}
		}
		
	}
	
	class onOffL implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			runFlag = !runFlag;
		}
		
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			try{
				selfThread.sleep(100);
			}catch(InterruptedException e){}
			
			if(runFlag)
				t.setText(Integer.toString(count++));
		}
	}
	public static void main(String[] args) {
	    Counter3 applet = new Counter3();
	    Frame aFrame = new Frame("Counter3");
	    aFrame.addWindowListener(
	      new WindowAdapter() {
	        public void windowClosing(WindowEvent e) {
	          System.exit(0);
	        }
	      });
	    aFrame.add(applet, BorderLayout.CENTER);
	    aFrame.setSize(300,200);
	    applet.init();
	    applet.start();
	    aFrame.setVisible(true);
	  }

}
